<%--                                                                       --%>
<%-- Copyright (c) 2005 BroadVision, Inc.  All rights reserved.            --%>
<%--                                                                       --%>
<%-- This software is copyrighted. Under the copyright laws, this software --%>
<%-- may not be copied, in whole or in part, without prior written consent --%>
<%-- of BroadVision, Inc. or its assignees. This software is provided      --%>
<%-- under the terms of a license between BroadVision and the recipient,   --%>
<%-- and its use is subject to the terms of that license.                  --%>
<%--                                                                       --%>
<%-- This software may be protected by one or more U.S. and International  --%>
<%-- patents.  Certain applications of BroadVision One-To-One software are --%>
<%-- covered by U.S. patent 5,710,887.                                     --%>
<%--                                                                       --%>
<%-- TRADEMARKS: BroadVision and BroadVision One-To-One are registered     --%>
<%-- trademarks of BroadVision, Inc., in the United States and the         --%>
<%-- European Community, and are trademarks of BroadVision, Inc., in other --%>
<%-- countries.  The BroadVision logo, is a trademark of BroadVision,      --%>
<%-- Inc., in the United States and other countries. Additionally, IONA    --%>
<%-- and Orbix are trademarks of IONA Technologies, Ltd.  RSA, MD5, and    --%>
<%-- RC2 are trademarks of RSA Data Security, Inc.                         --%>
<%--                                                                       --%>

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/webflow.tld" prefix="webflow" %>

<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Iterator" %>

<%@ page import="com.broadvision.data.client.DataManager" %>
<%@ page import="com.broadvision.data.client.Content" %>
<%@ page import="com.broadvision.data.common.ContentKey" %>
<%@ page import="com.broadvision.data.common.DataConstants" %>
<%@ page import="com.broadvision.data.common.ContentUID" %>

<%@ page import="com.broadvision.web.servlet.SessionVisitor" %>

<%@ page import="com.broadvision.portal.services.GenericPortalContent" %>
<%@ page import="com.broadvision.portal.services.PortalContent" %>
<%@ page import="com.broadvision.portal.services.PortalVisitor" %>

<%@ page import="java.io.IOException" %>
<%@ page import="java.util.StringTokenizer" %>

<%!
  /*
   * returns true if the String is null, empty or contains all spaces
   */
   boolean riIsEmptyString(String s) {
     return ((s == null) || (s.trim().length() == 0));
   }
%>

<%
  // get the request parameters and display error message for missing data
  String errString = "";
    
  int visitorId = 0;
  if( !riIsEmptyString(request.getParameter("VisitorId")) )
    visitorId = Integer.parseInt(request.getParameter("VisitorId"));
  else
    errString = "Error: VisitorId not found in request";
    
  int serviceId = 0;
  if( !riIsEmptyString(request.getParameter("ServiceId")))
    serviceId = Integer.parseInt(request.getParameter("ServiceId"));
  else
    errString = "Error: ServiceId not found in request";
  
  boolean scratchContent = true;
  int contentOID = 0;
  if( !riIsEmptyString(request.getParameter("ContentOID"))) {
    contentOID = Integer.parseInt(request.getParameter("ContentOID"));
    scratchContent = false;
  }
  String selections = request.getParameter("SelectedRelatedItems");
  //String selections = ":8201:8200:8199";

  int contentTypeId = 0;
  if( !riIsEmptyString(request.getParameter("ContentTypeId")))
    contentTypeId = Integer.parseInt(request.getParameter("ContentTypeId"));
  else
    errString = "Error: ContentTypeId not found in request";
  
  // The default related item is Editorial, so if nothing is passed in
  // then Editorial is assumed.
  int relCntTypeId = 2;
  if( !riIsEmptyString(request.getParameter("RelatedItemCntTypeId"))) {
    relCntTypeId = Integer.parseInt(request.getParameter("RelatedItemCntTypeId"));
  }

  if( !riIsEmptyString(errString) ) {
    %><%=errString%><%
    return;
  }

  // Instantiate PortalVisitor object
  PortalVisitor pVisitor = null;
  try {
    SessionVisitor sessionVisitor = SessionVisitor.getInstance(request.getSession());
    pVisitor = sessionVisitor.getPortalVisitor();
  }
  catch(Exception e) {
    %>Error instantiating Portal Visitor<%
    return;
  }

  // Hold a in-memory version of the Related Items.
  List relatedItemsNames = new ArrayList();
    
  // Generate the list of Related Items 
  try {
    if( !scratchContent) {
      GenericPortalContent portalContent = new GenericPortalContent(serviceId,
                              contentTypeId, 
                              contentOID, 
                              pVisitor);
        
      boolean filter = true;
      // if user is admin, then ignore qualifiers
      if( (request.getContextPath()).equals("/bvmc") ) {
        filter = false;
      }

      // Retrieve related items oid list 
      List relItemOids = portalContent.getRelatedItems(DataConstants.BV_ALL_DB_CONTENT, filter);
                                     
      // iterate through the list and get the name and id of related content
      Iterator iter = relItemOids.iterator();
      DataManager dataManager = new DataManager(visitorId);
      while ( iter.hasNext() ) {
        Content parentCnt = dataManager.getContent((ContentUID)iter.next());
        // relatedItemsNames.add(parentCnt.getStringValue("ED_NAME"));
        ContentKey contentKey = parentCnt.getKey();
        relatedItemsNames.add( (contentKey.getKey()).toString() );
      }
    }
    else {
      // handle scratch content here
      // This code is taken from AA for updateRelatedItems.xml
      DataManager dataManager = new DataManager(visitorId);
      if( !riIsEmptyString(selections)) {
        StringTokenizer tokens = new StringTokenizer(selections, ":");
        while (tokens.hasMoreTokens()) {
          String cntIdObj = tokens.nextToken();
          long cntId = Long.parseLong(cntIdObj);

          ContentUID cntUid = new ContentUID(contentTypeId, serviceId, cntId);
          Content cntItem = dataManager.getContent(cntUid);

          relatedItemsNames.add(cntItem.getStringValue("ED_NAME"));
        } 
      }   
    }
  }
  catch (Exception e) {
    %>Error getting related items.<%
    return;
  }
    
%>

<webflow:advance event='next' id='submit-url' />

<form method="post" name="content" enctype='' 
      action='<%= (String)pageContext.getAttribute("submit-url") %>' > 

  <table width="100%" cellspacing="0" cellpadding="0" border="0" summary="Main body">
    <tr>
      <td class="column2" valign="top">
        <div class="pageTitle"><bean:message key="ep.application.RelatedContent"/></div>
        <div class="blockTitle">
          <span class="left">&nbsp;</span>
          <span class="right">&nbsp;</span>
        </div>

        <div class="blockWrap">
          <table class="labelForm" width="100%" cellspacing="0" cellpadding="2" summary="Form fields">
            <tr>    
              <td nowrap class="label"><bean:message key="ep.application.RelatedContent"/></td>
            </tr>
    

    <%
      // Output each of the Related Items in our list.    
      int relItemNum = 1;
      Iterator iterNames = relatedItemsNames.iterator();
      String listID="listEven";
      
      while( iterNames.hasNext() ) {
        String name = (String)iterNames.next();
        if(relItemNum%2==0)
          listID = "listEven";
        else
          listID = "listOdd";
    %>    
            <tr class="<%=listID%>" >
              <td headers="Name"  align="left">
                <%=name%>
              </td>
            </tr>
    
    <%
        // One more put out.
        relItemNum++;
      }
    %>

            <tr align=right>
              <td colspan=2 align=right>
                <div class="lineWrap">
                  <input type="submit" name="Cancel" class="pageButton" value="Done"/>
                </div>
              </td>
            </tr>
          </table>
        </div>
      </td>
     </tr>
   </table>
</form>
